﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;

public partial class mailmerge : System.Web.UI.Page
{
    DataSet dseInputInfo = new DataSet();
    DataSet dsePageInfo = new DataSet();
    HtmlForm frmObj;
    security hdds;
    string strPagesetRowId;
    
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["theme"].ToString();
        this.Title = "MaxBlox";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            hdds = new security();
            lblMessage.Text = "";
            if (Session["userid"] == null) Response.Redirect(hdds.SessionExpiryURL);
            if (Session["userid"].ToString() == "") Response.Redirect(hdds.SessionExpiryURL);

            string strErrorMsg = "";
            if (!hdds.IsValidPageURL(ref strErrorMsg))
            {
                lblMessage.Text = wrapItAsMessage(strErrorMsg, true);
                TABLE1.Visible = false;
                return;
            }

            if (Request.QueryString["mn"] != null)
                hdds.logMenuClick(Request.QueryString["mn"].ToString());

            if (Request.QueryString["MK"] != null && Request.QueryString["MK"].ToString() != "")
                Response.Redirect(Request.Url.AbsoluteUri.Replace("mailmerge.aspx", "dynamicscreen.aspx"));

            if (this.Master.FindControl("Form1") != null)
                frmObj = (HtmlForm)this.Master.FindControl("Form1");

            strPagesetRowId = Request.QueryString["pgs_id"].ToString();

            PageInfoLoad PIL = new PageInfoLoad();
            dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

            if (!Page.IsPostBack)
            {
                string ret = MBLocale.MBLocalization.getDateFormat(HttpContext.Current.Session["userlocale"].ToString());
                Cal2.Format = ret + " hh:mm tt";
                loadObjectList();
                loadEmailTemplateList();
                loadOwneridDropDown();
                CheckForChangeOwner();
                checkEditOperation();
                getpageicons();
            }
            AddPageToolTip(dsePageInfo.Tables["Page"].Rows[0], ref lblHeader);
            isViewMode();
            AddStatisticsSection(dsePageInfo);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Mail merge: Error : Page_Load : " + ex.Message);
        }
    }

    private bool checkEditOperation()
    {
        bool bEdit = false;
        try
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["PK"] != null)
                {
                    lblHeader.Text = " Mail Merge - Edit";
                    bEdit = true;
                    getData();
                }
                if (Request.QueryString["CPY"] != null)
                {
                    if (Request.QueryString["CPY"] == "0")
                    {
                        lblHeader.Text = " Mail Merge - Copy";
                        bEdit = false;
                    }
                }
                if (Request.QueryString["VMODE"] != null)
                    if (Request.QueryString["VMODE"] == "1")
                    {
                        lblHeader.Text = " Mail Merge - View";
                        tr_Process_Status.Visible = true;
                    }
                if (bEdit)
                {
                    btnSave.Visible = false;
                    btnUpdate.Visible = true;
                }
                else
                {
                    btnUpdate.Visible = false;
                    btnSave.Visible = true;
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Mail merge: checkEditOperation : Error : " + ex.Message);
            return true;
        }
        return true;
    }
    #region View mode functions
    private void isViewMode()
    {
        security HDS = new security();
        bool create = false, edit = false, delete = false;
        try
        {
        if (Request.QueryString["VMODE"] != null)
            if (Request.QueryString["VMODE"] == "1")
            {
                DynamicDisplayI ddi = new DynamicDisplayI();
                HtmlTable ht = (HtmlTable)frmObj.FindControl("ContentPlaceHolder3").FindControl("TABLE1");
                ddi.disableControls(ht);
                ddi = null;


                HDS.getPagesetRights(strPagesetRowId, ref create, ref edit, ref delete);

                Label cc = (Label)frmObj.FindControl("ContentPlaceHolder3").FindControl("lblViewButton");
                if (cc == null) return;

                if (edit)
                {
                    ImageButton bEdit = new ImageButton();
                    bEdit = new ImageButton();
                    bEdit.ID = "btnEditTop";
                    bEdit.ImageUrl = "images/mb_button_edit.gif";
                    bEdit.ToolTip = "Edit";
                    bEdit.CausesValidation = false;
                    // bEdit.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnEditTop','Loading...');");
                    bEdit.Click += new ImageClickEventHandler(btnEdit_Click);
                    cc.Controls.Add(bEdit);
                    cc.Controls.Add(new LiteralControl("&nbsp;"));
                }

                if (create)
                {
                    ImageButton bCopy = new ImageButton();
                    bCopy = new ImageButton();
                    bCopy.ID = "btnCpyTop";
                    bCopy.ToolTip = "Copy";
                    bCopy.CausesValidation = false;
                    bCopy.ImageUrl = "images/mb_button_copy.gif";
                    //bCopy.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnCpyTop','Loading...');");
                    bCopy.Click += new ImageClickEventHandler(btnCpy_Click);
                    cc.Controls.Add(bCopy);
                    cc.Controls.Add(new LiteralControl("&nbsp;"));
                }

                if (delete)
                {
                    bool bDeleteOverride = true;
                    String sDelete_RowId = "";
                    getDelOverrideAccess(ref bDeleteOverride, dsePageInfo.Tables["page"].Rows[0]["page_id"].ToString(), dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString(), ref sDelete_RowId);

                    ImageButton bDel = new ImageButton();
                    bDel = new ImageButton();
                    bDel.ID = "btnDelTop";
                    bDel.ToolTip = "Delete";
                    bDel.CausesValidation = false;
                    bDel.ImageUrl = "images/mb_button_delete.gif";
                    //b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnDelTop','Deleting...');");           
                    if (bDeleteOverride)
                        bDel.OnClientClick = @"javascript:if(!confirm(""Are you sure you want to delete this Record ?"")){return false;};";
                    else
                        bDel.OnClientClick = @"javascript:alert('You do not have access to delete');return false;";
                    bDel.Click += new ImageClickEventHandler(btnDel_Click);
                    cc.Controls.Add(bDel);
                    cc.Controls.Add(new LiteralControl("&nbsp;"));
                }
                putPrintButtons();
                btnSave_top.Visible = false;
                btnUpdate_top.Visible = false;
                btnReset_top.Visible = false;
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error: RoleSecurity: isViewMode()" + e.Message);
        }
    }
    private void putPrintButtons()
    {
        security HDS = new security();
        try
        {
            if (HDS.getObjectRightsForUser(dsePageInfo.Tables["Page"].Rows[0]["object_id"].ToString(), "read"))
            {
                Label cc = (Label)frmObj.FindControl("ContentPlaceHolder3").FindControl("lblPrintButton");
                if (cc == null) return;

                ImageButton bPrint = new ImageButton();
                bPrint = new ImageButton();
                bPrint.ID = "btnprintTop";
                bPrint.ToolTip = "Printer friendly page";
                bPrint.CausesValidation = false;
                bPrint.ImageUrl = "images/mb_button_print.GIF";
                //b.Attributes.Add("OnClick", "javascript:disableThis('ctl00_ContentPlaceHolder3_btnCpyTop','Loading...');");
                //b.Click += new ImageClickEventHandler(btnCpy_Click);
                bPrint.OnClientClick = "javascript:Popup=(window.open('Print.aspx?pgs_id=" + strPagesetRowId + "&PK=" + Request.QueryString["PK"].ToString() + "&mn=" + Request.QueryString["mn"].ToString() + "','Popup','toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=800,height=630,left=100,top=30')||window).focus(); return false;";
                cc.Controls.Add(bPrint);
                cc.Controls.Add(new LiteralControl("&nbsp;"));
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error: RoleSecurity: putHeaderButtons()" + e.Message);
        }
    }

    protected void btnEdit_Click(object sender, EventArgs e)
    {
        try
        {
            bool bEditOverride = true;
            String sEdit_RowId = "";
            getEditOverrideAccess(ref bEditOverride, dsePageInfo.Tables["page"].Rows[0]["page_id"].ToString(), dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString(), ref sEdit_RowId);

            if (bEditOverride)
            {
                string url = Request.Url.ToString().ToLower();
                url = url.ToString().Replace("&vmode=1", "").Replace("&vmode=0", "");
                if (url != "")
                    if (Request.QueryString["PK"] != null)
                        Response.Redirect(url, true);
            }
            else
            {
                String url = @"" + "NoAccess.aspx" + @"?pgs_id=" + strPagesetRowId + "&PK=" + sEdit_RowId
                                    + "&mn=" + Request.QueryString["mn"] + @"";
                Response.Redirect(url, true);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: RoleSecurity: btnEdit_Click() : " + ex.Message);
        }

    }
    protected void btnCpy_Click(object sender, EventArgs e)
    {
        try
        {
            string url = Request.Url.ToString().ToLower();
            url = url.ToString().Replace("&vmode=1", "").Replace("&vmode=0", "");
            url = url + "&CPY=0";
            if (url != "")
                if (Request.QueryString["PK"] != null)
                    Response.Redirect(url, true);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: RoleSecurity: btnCpy_Click() : " + ex.Message);
        }
    }
    protected void btnDel_Click(object sender, EventArgs e)
    {
        try
        {
            string strDelKey = "";
            string strPagesetRowId = "";
            if (Request.QueryString["pgs_id"] != null)
                strPagesetRowId = Request.QueryString["pgs_id"].ToString();

            if (Request.QueryString["PK"] != null)
                strDelKey = Request.QueryString["PK"].ToString().Replace("'", "''");

            if (strDelKey != "")
            {
                string ret = Navigator.getURL(Request.Url.ToString());
                if (ret != "")
                {
                    if (ret.Contains("DisplayGrid.aspx"))
                    {
                        DataSet dsePageInfo = new DataSet();
                        PageInfoLoad PIL = new PageInfoLoad();
                        dsePageInfo = PIL.GetPageSetPageCtrlInfo(strPagesetRowId);

                        Master MA = new Master();
                        bool blnStatus = MA.ProcessOperation(dsePageInfo, strDelKey, "DELETE");
                        Response.Redirect(ret, true);
                    }
                    else Response.Redirect(ret, true);
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: RoleSecurity: btnDel_Click() : " + ex.Message);
        }
    }

    private void getEditOverrideAccess(ref bool bEdit, String Page_id, string Object_Table_Name, ref String Edit_rowid)
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            DataSet dsTemp = HDD.GetDataset("select * from sy_object_access_override where object='" + Page_id + "' and action='edit' and active='1';");

            foreach (DataRow dr in dsTemp.Tables[0].Rows)
            {
                switch (dr["action"].ToString().ToLower())
                {
                    case "edit":
                        bool bRecord = getOverrideForThisRecord(dr["condition"].ToString());
                        if (bRecord)
                        {
                            if (dr["mode"].ToString().ToLower() == "enable")
                                bEdit = true;
                            else if (dr["mode"].ToString().ToLower() == "disable")
                                bEdit = false;
                            Edit_rowid = dr["af_row_id"].ToString();
                        }
                        break;
                    default:
                        break;
                }
            }
            dsTemp.Dispose();
            dsTemp = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: RoleSecurity: getEditOverrideAccess() : " + ex.Message);
        }
    }
    private bool getOverrideForThisRecord(String Condition)
    {
        bool bRet = true;
        try
        {
            HDDatabase HDD = new HDDatabase();
            String sSql = "select af_row_id from " + dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString() + " where af_row_id='" + Request.QueryString["PK"] + "'";
            if (Condition != "")
                sSql = "select af_row_id from " + dsePageInfo.Tables["page"].Rows[0]["page_table_name"].ToString() + " where af_row_id='" + Request.QueryString["PK"] + "' and " + Condition;

            String sRet = HDD.GetColumnValue(sSql);
            if (sRet != "")
                bRet = true;
            else
                bRet = false;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : RoleSecurity: getOverrideForThisRecord() : " + ex.Message);
        }
        return bRet;
    }
    private void getDelOverrideAccess(ref bool bDelete, String Page_id, string Object_Table_Name, ref String Delete_rowid)
    {
        try
        {
            HDDatabase HDD = new HDDatabase();
            DataSet dsTemp = HDD.GetDataset("select * from sy_object_access_override where object='" + Page_id + "' and action='delete' and active='1';");

            foreach (DataRow dr in dsTemp.Tables[0].Rows)
            {
                switch (dr["action"].ToString().ToLower())
                {
                    case "delete":
                        bool bRecord1 = getOverrideForThisRecord(dr["condition"].ToString());
                        if (bRecord1)
                        {
                            if (dr["mode"].ToString().ToLower() == "enable")
                                bDelete = true;
                            else if (dr["mode"].ToString().ToLower() == "disable")
                                bDelete = false;
                            Delete_rowid = dr["message"].ToString();
                        }
                        break;
                    default:
                        break;
                }
            }
            dsTemp.Dispose();
            dsTemp = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : RoleSecurity: getDelOverrideAccess() : " + ex.Message);
        }
    }
    #endregion

    #region Load Owner field
    private void loadOwneridDropDown()
    {
        HDDatabase Hdd = new HDDatabase();
        BindControl BC = new BindControl();
        try
        {
            if (Request.QueryString["PK"] == null)
            {
                p_mail_owner_id.Value = Session["user_afrowid"].ToString();
                txt_p_mail_owner_id.Text = Session["userid"].ToString();
            }
            if (Request.QueryString["PK"] != null)
            {
                if (Request.QueryString["CPY"] != null)
                {
                    p_mail_owner_id.Value = Session["user_afrowid"].ToString();
                    txt_p_mail_owner_id.Text = Session["userid"].ToString();
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Mail merge: loadOwneridDropDown : Error : " + ex.Message);
        }
        finally
        {
            Hdd = null;
            BC = null;
        }
    }

    private void CheckForChangeOwner()
    {
        try
        {
            security sec = new security();
            bool status = false;
            status = sec.getRightsForMRUObjects(strPagesetRowId, "change_owner");
            if (status == false)
            {
                txt_p_mail_owner_id.Enabled = false;
                imgOwnerSearch.Visible = false;
            }
            sec = null;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Mail merge: CheckForChangeOwner : Error : " + ex.Message);
        }
    }
    #endregion

    #region Page Icon and Tooltip
    private void getpageicons()
    {
        PageIcons icons = new PageIcons();
        HDDatabase Hdd = new HDDatabase();
        try
        {
            string strPagesetRowID = Request.QueryString["pgs_id"].ToString();
            lblHeader.Text = "&nbsp;" + icons.geticontextfrompageset(strPagesetRowID, 2) + "&nbsp;" + lblHeader.Text;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error :getpageicons() " + ex.Message);
            lblHeader.Text = "<img src=" + PageIcons.strdefaulticon.ToString() + "></img>&nbsp;" + lblHeader.Text;
        }
        finally
        {
            icons = null;
            Hdd = null;
        }
    }

    private void AddPageToolTip(DataRow drpage, ref Label lblHeader)
    {
        if (drpage != null)
        {
            if (!Page.IsPostBack)
                lblHeader.Text = lblHeader.Text + getTootipIcon(drpage);
            Literal lit = new Literal();
            lit.Text = getTooltipContent(drpage);
            td_Page_ToopTip.Controls.Add(lit);
        }
    }

    private string getTootipIcon(DataRow droPage)
    {
        try
        {
            if (!droPage.Table.Columns.Contains("page_desc")) return "";
            if (droPage["page_desc"].ToString().Trim() == "") return "";
            return "&nbsp;<img id=\"page_tooltip_img\" style=\"cursor:pointer;\" src=\"Images/collapse3.gif\" onClick=\"javascript:showHideTooltipDIV();\" border=\"0\"></img>";
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string getTooltipContent(DataRow droPage)
    {
        if (!droPage.Table.Columns.Contains("page_desc")) return "";
        if (droPage["page_desc"].ToString().Trim() == "") return "";
        return getContent(HttpContext.Current.Server.MapPath("") + @"\scripts\pagetooltipcontent.txt").Replace("<<content>>", CommonFunctions.SafeEncode(droPage["page_desc"].ToString()));
    }

    private string getContent(string fileName)
    {
        try
        {
            if (!File.Exists(fileName))
                return "";
            string temp = "";
            StreamReader sr = new StreamReader(fileName);
            temp = sr.ReadToEnd();
            sr.Close();
            sr = null;
            return temp;
        }
        catch (Exception e)
        {
            return "";
        }
    }

    private string wrapItAsMessage(string msg, bool isError)
    {
        return "<div class=\"" + (isError == true ? "mbErrorMessage" : "mbMessage") + "\">" + msg + "</div>";
    }
    #endregion

    #region Load Objects & email template

    private void AddDefaultObjects(ref DataTable dtInput) // Added by 'Imran Gani' on 15-Oct-2013, to handle configured objects
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            string objectids = "";
            if (dtInput != null)
            {
                foreach (DataRow dr in dtInput.Rows)
                    objectids += "'" + dr["object_id"].ToString() + "',";
                if (objectids.EndsWith(","))
                    objectids = objectids.TrimEnd(',');
            }
            string strSQL = "";
            if (objectids.Trim() == "")
                strSQL = "select mem_id,mem_name,mem_value2 from sy_acr_mem where acr_id = '1b8bcdd101823723' and mem_value1 = 'true' order by mem_name";
            else
                strSQL = "select mem_id,mem_name,mem_value2 from sy_acr_mem where acr_id = '1b8bcdd101823723' and mem_value1 = 'true' and mem_value1 not in (" + objectids + ") order by mem_name";
            DataTable dt = HDD.GetDataTable(strSQL);

            if (dt != null)
                if (dt.Rows.Count > 0)
                    foreach (DataRow dr in dt.Rows)
                    {
                        DataRow drInput = dtInput.NewRow();
                        drInput["object_name"] = dr["mem_name"].ToString();
                        drInput["object_id"] = dr["mem_id"].ToString();
                        drInput["af_row_id"] = dr["mem_value2"].ToString();
                        dtInput.Rows.Add(drInput);
                    }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddDefaultObjects : " + ex.Message);
        }
        finally
        {
            HDD = null;
        }
    }

    private void loadObjectList()
    {
        HDDatabase hd = new HDDatabase();
        DataTable dt = new DataTable();
        SecurityFilter objSec = new SecurityFilter();
        try
        {
            //Adding Queries
            string Sql = objSec.applysecurity("Select * from sy_obj");
            dt = hd.GetDataTable(Sql);
            AddDefaultObjects(ref dt);
            p_Mail_Merge_Source_ID.Items.Clear();
            p_Mail_Merge_Source_ID.Items.Add(new ListItem("--Select a Table/Query--", ""));
            p_Mail_Merge_Source_ID.Items.Add(new ListItem("--Tables--", ""));
            foreach (DataRow dr in dt.Select("", "object_name asc"))
                if (hdds.getObjectRightsForUser(dr["object_id"].ToString(), "read"))
                    p_Mail_Merge_Source_ID.Items.Add(new ListItem(dr["object_name"].ToString(), "OBJECT@" + dr["af_row_id"].ToString()));
            
            //Adding Queries
            //ArrayList alList = new ArrayList();
            p_Mail_Merge_Source_ID.Items.Add(new ListItem("--Queries--", ""));
            Sql = "Select * from sy_report_sql";
            Sql = objSec.applysecurity(Sql);
            dt = hd.GetDataTable(Sql);
            foreach (DataRow dr in dt.Select())
            {
                ListItem liObject = new ListItem(dr["report_base_name"].ToString(), "SQL@" + dr["af_row_id"].ToString());
                if (dr["report_base_param"].ToString().ToUpper().StartsWith("PARAMETERS") || dr["report_base_sql"].ToString().Contains("$") || dr["report_base_sql"].ToString().Contains("#"))
                    continue; //alList.Add(liObject);
                else
                    p_Mail_Merge_Source_ID.Items.Add(liObject);
            }
            //p_Mail_Merge_Source_ID.Items.Add(new ListItem("--Parameter Queries--", ""));
            //foreach (ListItem li in alList)
            //    p_Mail_Merge_Source_ID.Items.Add(li);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("loadObjectList : Error : " + ex.Message);
        }
        finally
        {
            dt.Dispose();
            hd = null;
            objSec = null;
        }
    }

    private void loadEmailTemplateList()
    {
        HDDatabase hd = new HDDatabase();
        DataTable dt = new DataTable();
        SecurityFilter objSec = new SecurityFilter();
        try
        {
            string Sql = objSec.applysecurity("Select * from sy_email_template");
            dt = hd.GetDataTable(Sql);
            p_Mail_Merge_Email_Template.Items.Clear();
            p_Mail_Merge_Email_Template.Items.Add(new ListItem("--Select a Email Template--", ""));
            foreach (DataRow dr in dt.Select("", "name asc"))
                p_Mail_Merge_Email_Template.Items.Add(new ListItem(dr["name"].ToString(), dr["af_row_id"].ToString()));
            if (dt.Rows.Count == 0)
                lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;You do not have email template record. Please create an email template for this mail.", false);
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("loadEmailTemplateList : Error : " + ex.Message);
        }
        finally
        {
            dt.Dispose();
            hd = null;
            objSec = null;
        }
    }
    #endregion

    private void getData()
    {
        HDDatabase hdd = new HDDatabase();
        try
        {
            foreach (DataRow dr in dsePageInfo.Tables["page"].Rows)
            {
                string sObject_id = dr["object_id"].ToString();
                if (hdds.getObjectRightsForUser(dr["object_id"].ToString(), "read"))
                {
                    DataTable dt = hdd.GetDataTable("select * from " + dr["page_table_name"].ToString() + " where af_row_id = '" + Request.QueryString["PK"].ToString() + "'");
                    dt.TableName = dr["page_id"].ToString();
                    dseInputInfo.Tables.Add(dt.Copy());

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        p_Mail_Merge_Name.Text = dt.Rows[0]["name"].ToString();
                        p_Mail_Merge_Description.Text = dt.Rows[0]["description"].ToString();
                        p_Mail_Merge_Source_ID.SelectedValue = dt.Rows[0]["source_type"].ToString() + "@" + dt.Rows[0]["source_id"].ToString();
                        p_Mail_Merge_Email_Template.SelectedValue = dt.Rows[0]["email_template"].ToString();
                        p_Mail_Merge_From_Mail.Text = dt.Rows[0]["from_mail"].ToString();
                        p_Mail_Merge_Delivery_Date.Text = dt.Rows[0]["delivery_date"].ToString();
                        p_Mail_Merge_To_Mail.Text = dt.Rows[0]["to_mail"].ToString();
                        LoadEditPage LEP = new LoadEditPage();
                        txt_p_mail_owner_id.Text = LEP.GetUserIDFromAfrowid(dt.Rows[0]["owner_id"].ToString());
                        p_mail_owner_id.Value = dt.Rows[0]["owner_id"].ToString();
                        p_Mail_Merge_Process_Status.Text = dt.Rows[0]["process_status"].ToString();
                    }
                }
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error: Mail merge: getData() : " + ex.Message);
        }
    }

    private void AddStatisticsSection(DataSet dsPageInfo)
    {
        try
        {
            if (Request.QueryString["CPY"] == null && Request.QueryString["PK"] != null && dsPageInfo != null)
            {
                DynamicDisplayI DDI = new DynamicDisplayI();
                DataTable dtChilds = DDI.getAllChildObjects(strPagesetRowId);
                if (dtChilds != null)//implemenetd by sanal on April 03, 2008
                    if (dtChilds.Rows.Count > 0)
                    {
                        DDI.getPagesetandLoad(dtChilds, frmObj);
                        if (Request.QueryString["isDDE"] == null)//Added by srivatsan for DDE changes
                            Navigator.storeURL(Request.Url.ToString(), IsPostBack, false, false);
                    }
                DDI = null;
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : AddStatisticsSection :" + ex.Message);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (checkSourceRecordExist())
            {
                lbl_confirmMsg.Text = "<img alt='Information' src='images/info.gif' />&nbsp;The emails will be processed now to be delivered at " + p_Mail_Merge_Delivery_Date.Text + ". Continue?";
                lbl_confirmMsg1.Text = "<img alt='Information' src='images/info.gif' />&nbsp;The emails will be processed now to be delivered at " + p_Mail_Merge_Delivery_Date.Text + ". Continue?";
                pnl_confirm.Visible = true;
                pnl_confirm1.Visible = true;
                btnSave.Enabled = false;
                btnSave.Text = "Saving...";
                btnSave_top.Enabled = false;
                btnSave_top.Text = "Saving...";
            }
            else
            {
                lbl_confirmMsg.Text = "";
                lbl_confirmMsg1.Text = "";
                pnl_confirm.Visible = false;
                pnl_confirm1.Visible = false;
                btnSave.Enabled = true;
                btnSave.Text = "Save";
                btnSave_top.Enabled = true;
                btnSave_top.Text = "Save";
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Mail merge: btnSave_Click() : " + ex.Message);
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            if (SaveData("Update", false))
            {
                string refURL = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
                if (refURL.Length > 0)
                    Response.Redirect(refURL);
                else
                    lblMessage.Text = wrapItAsMessage("Data Updated Successfully", false);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Mail Merge: btnSave_Click() : " + ex.Message);
        }
    }
    protected void btnReset_Click(object sender, EventArgs e)
    {
        try
        {
            Response.Redirect(Request.Url.ToString());
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Mail merge : btnReset_Click() : " + ex.Message);
        }
    }
    protected void btnYes_Click(object sender, EventArgs e)
    {
        if (SaveData("Insert", true))
        {
            string refURL = "DisplayGrid.aspx?pgs_id=" + Request.QueryString["pgs_id"].ToString() + "&mn=" + Request.QueryString["mn"].ToString();
            if (refURL.Length > 0)
                Response.Redirect(refURL);
            else
                lblMessage.Text = wrapItAsMessage("Data Inserted Successfully", false);
        }
        pnl_confirm.Visible = false;
        pnl_confirm1.Visible = false;
        btnSave.Enabled = true;
        btnSave.Text = "Save";
        btnSave_top.Enabled = true;
        btnSave_top.Text = "Save";
    }

    protected void btnNo_Click(object sender, EventArgs e)
    {
        pnl_confirm.Visible = false;
        pnl_confirm1.Visible = false;
        btnSave.Enabled = true;
        btnSave.Text = "Save";
        btnSave_top.Enabled = true;
        btnSave_top.Text = "Save";
    }

    private bool ValidateEmailField(DataTable dt_src)
    {
        CommonFunctions cmf = new CommonFunctions();
        bool sRet = false;
        try
        {
            string MailId = p_Mail_Merge_From_Mail.Text.Trim().Replace(" ", "_");
            if (MailId.Contains(",")) MailId.Replace(",", ";");
            if (MailId.TrimEnd(';').Split(';').Length > 1)
            {
                lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Invalid 'From' email id. Provide an email id or select a field.", false);
                return sRet;
            }

            if (!cmf.ValidateEmailID(MailId))
                if (!dt_src.Columns.Contains(MailId))
                {
                    lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Invalid 'From' email id. Provide an email id or select a field.", false);
                    return sRet;
                }

            MailId = p_Mail_Merge_To_Mail.Text.Trim().Replace(" ", "_");
            if (MailId.Contains(",")) MailId.Replace(",", ";");
            if (MailId.TrimEnd(';').Split(';').Length > 1)
            {
                lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Invalid 'To' email id. Provide an email id or select a field.", false);
                return sRet;
            }

            if (!cmf.ValidateEmailID(MailId))
                if (!dt_src.Columns.Contains(MailId))
                {
                    lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Invalid 'To' email id. Provide an email id or select a field.", false);
                    return sRet;
                }

            sRet = true;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Mailmerge : SaveData() : " + ex.Message);
            return sRet;
        }
        return sRet;
    }

    private bool checkSourceRecordExist()
    {
        bool sRet = false;
        DataTable dt = new DataTable();
        HDDatabase hdd = new HDDatabase();
        SecurityFilter objSec = new SecurityFilter();
        try
        {
            string[] strSourceType = p_Mail_Merge_Source_ID.SelectedValue.Split('@');
            if (strSourceType.Length != 0)
            {
                string strSource_type = strSourceType[0];
                string strSource_id = strSourceType[1];
                hf_ObjectSQL.Value = "";
                switch (strSource_type.ToLower())
                {
                    case "object":
                        string sTableObj = hdd.GetColumnValue("select object_table from sy_obj where af_row_id = '" + strSource_id + "';");
                        string sObjSQL = objSec.applysecurity("select * from " + sTableObj);
                        dt = hdd.GetDataTable(sObjSQL);
                        if (dt.Rows.Count > 0)
                        {
                            hf_ObjectSQL.Value = sObjSQL;
                            sRet = true;
                        }
                        break;
                    case "sql":
                        string sql = hdd.GetColumnValue("select report_base_sql from sy_report_sql where af_row_id = '" + strSource_id + "';");
                        dt = hdd.GetDataTable(sql);
                        if (dt.Rows.Count > 0)
                            sRet = true;
                        break;
                }
                if (sRet)
                    sRet = ValidateEmailField(dt);
                else
                    lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;No records available in the selected source (" + p_Mail_Merge_Source_ID.SelectedItem.Text + ").", false);
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Mailmerge : SaveData() : " + ex.Message);
            return sRet;
        }
        return sRet;
    }

    private bool SaveData(string sOperation, bool isSaveMode)
    {
        bool blnStatus = true;
        string sProcessRowId;
        try
        {
            ScreenReader SR = new ScreenReader();
            sProcessRowId = "af07eaf26b4f4768"; // Process Row_id for mail merge
            dseInputInfo = SR.CaptureData(strPagesetRowId, frmObj, dsePageInfo, isSaveMode);
            if (SR.errormessage != "")
            {
                lblMessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data " + sOperation + " not successful. Error: " + HttpUtility.HtmlEncode(SR.errormessage), true); ;
                return false;
            }
            string[] strSourceType = dseInputInfo.Tables[0].Rows[0]["source_id"].ToString().Split('@');
            if (strSourceType.Length > 1)
            {
                dseInputInfo.Tables[0].Rows[0]["source_type"] = strSourceType[0];
                dseInputInfo.Tables[0].Rows[0]["source_id"] = strSourceType[1];

                if (strSourceType[0].ToUpper() == "OBJECT")
                    getEmailFields(dseInputInfo, strSourceType[1]);
            }
            dseInputInfo.Tables[0].Rows[0]["object_sql"] = hf_ObjectSQL.Value;
            dseInputInfo.Tables[0].Rows[0]["owner_id"] = p_mail_owner_id.Value;
            dseInputInfo.Tables[0].Rows[0]["process_row_id"] = sProcessRowId;
            dseInputInfo.Tables[0].Rows[0]["process_status"] = "Initiated";
            Master MA = new Master();
            blnStatus = MA.ProcessOperation(dsePageInfo, dseInputInfo, sOperation.ToUpper());
            if (!blnStatus)
                lblMessage.Text = wrapItAsMessage("<img src=\"Images/error.gif\" alt=\"Error\"></img>&nbsp;" + "Data " + sOperation + " not successful. Error: " + HttpUtility.HtmlEncode(MA.ErrorMessage), true);
            else
            {
                ActivateProcessManager(sProcessRowId, dseInputInfo.Tables[0].Rows[0]["af_row_id"].ToString());
                lblMessage.Text = wrapItAsMessage("&nbsp;<img src='Images/info.gif' border='0'>&nbsp;Data " + sOperation + " Successfully.", false);//changed by prithi on 07-Aug-2008
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("Error : Mailmerge : SaveData() : " + ex.Message);
            return blnStatus;
        }
        return blnStatus;
    }
    private void ActivateProcessManager(string sProcessRowId, string sMailMergeRowId)
    {
        ScreenReader SR = new ScreenReader();
        SqlCommand sqlCommand = null;
        SqlConnection sqlConn = null;
        try
        {
            string sProcessStaRowId = SR.getHashKey();

            string sSql = "INSERT INTO [sy_process_statistics] ([Process_row_id],[initiated_by],[functional_row_id],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                 " VALUES ('" + sProcessRowId + "','" + Session["user_afrowid"].ToString() + "','" + sMailMergeRowId + "','" + sProcessStaRowId +
                 "','" + Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + Session["user_afrowid"].ToString() + "', 'e51e0327224a2eb9');";

            sqlConn = new SqlConnection(HttpContext.Current.Session["dbcon"].ToString());
            sqlCommand = new SqlCommand(sSql, sqlConn);
            sqlConn.Open();
            int Exe = sqlCommand.ExecuteNonQuery();
            sqlConn.Close();
            if (Exe > 0)
            {
                sSql = "INSERT INTO [sy_processes] ([Process_row_id],[Statistics_row_id],[Company_id],[User_id],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id])" +
                     " VALUES ('" + sProcessRowId + "','" + sProcessStaRowId + "','" + Session["company_afrowid"].ToString() + "','" + Session["user_afrowid"].ToString() + "','" + SR.getHashKey() +
                     "','" + Session["user_afrowid"].ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + DateTime.Now.ToUniversalTime().ToString() + "','" + Session["user_afrowid"].ToString() + "', 'e51e0327224a2eb9');";
                sqlConn = new SqlConnection(HttpContext.Current.Session["servercon"].ToString());
                sqlCommand = new SqlCommand(sSql, sqlConn);
                sqlConn.Open();
                sqlCommand.ExecuteNonQuery();
            }
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("mailmerge: ActivateProcessManager : Error : " + ex.Message);
        }
        finally
        {
            if (sqlCommand != null)
                sqlCommand.Dispose();
            if (sqlConn != null)
            {
                if (sqlConn.State.Equals(ConnectionState.Open))
                    sqlConn.Close();
                sqlConn.Dispose();
            }
            SR = null;
        }
    }

    private void getEmailFields(DataSet dseInputInfo, string sObjectID)
    {
        HDDatabase HDD = new HDDatabase();
        try
        {
            string sFromField = HDD.GetColumnValue("select attrib_id from sy_obj_att where attrib_name = '" + dseInputInfo.Tables[0].Rows[0]["from_mail"].ToString() + "' and object_id = '" + sObjectID + "';");
            string sToField = HDD.GetColumnValue("select attrib_id from sy_obj_att where attrib_name = '" + dseInputInfo.Tables[0].Rows[0]["to_mail"].ToString() + "' and object_id = '" + sObjectID + "';");
            if (sFromField != "")
                dseInputInfo.Tables[0].Rows[0]["from_mail"] = sFromField;
            if (sToField != "")
                dseInputInfo.Tables[0].Rows[0]["to_mail"] = sFromField;
        }
        catch (Exception ex)
        {
            LogWriter.WriteLog("mailmerge: getEmailFields : Error : " + ex.Message);
        }
    }
}